<template>
  <!-- 质量整改通知单的操作页，包括：填报 0 ，调整 1 ，查看 2 -->
  <base-breadcrumb :title="$route.meta.title">
    <a-spin :spinning="loading">
      <a-card :bordered="false" class="base-info-style" v-for="(detail, index) in form.detail" :key="detail.id">
          <div v-if="index" :key="detail.id + 'next'">
            <!-- 继续处理 -->
            <ComForm :form="detail" title="继续处理" :onlyRead="true" :showProjectPosition="false" :showPlanBoardVisible="true" :defaultPlanBoardVisible="defaultPlanBoardVisible(index)" />
             <!-- 风险跟踪检查信息 -->
             <ComTable :dataSource="detail.checks['gz']" v-if="detail.checks && detail.checks['gz']" :title="'风险跟踪检查信息'" :onlyRead="true" :showPlanBoardVisible="true" :defaultPlanBoardVisible="defaultPlanBoardVisible(index)" />
            <!-- 风险过程检查信息 -->
            <ComTable :dataSource="detail.checks['gc']" :showRiskMonitorTimeLimit="false" v-if="detail.checks && detail.checks['gc']" :title="'风险过程检查信息'" :onlyRead="true" :showPlanBoardVisible="true" :defaultPlanBoardVisible="defaultPlanBoardVisible(index)" />
             <!-- 验证结果 -->
             <ComResult :form="detail.result" :onlyRead="true"  v-if="detail.result" :showPlanBoardVisible="true" :defaultPlanBoardVisible="defaultPlanBoardVisible(index)" />
          </div>
          <div v-else>
            <!-- 基本信息 -->
            <BaseInfo ref="BaseInfo" :form="detailForm" :onlyRead="true" />
            <!-- 风险上报信息 -->
            <RiskReportingInfo :form="detailForm" :onlyRead="true" :showPlanBoardVisible="true" :defaultPlanBoardVisible="defaultPlanBoardVisible(index)" />
            <!-- 风险复核信息 -->
            <RiskReviewInfo :form="detailForm" :onlyRead="true" :showPlanBoardVisible="true" :defaultPlanBoardVisible="defaultPlanBoardVisible(index)" />
            <!-- 风险处理方案信息 -->
            <RiskTreatmentPlanInfo ref="RiskTreatmentPlanInfo" :form="form" :onlyRead="true" :showPlanBoardVisible="true" :defaultPlanBoardVisible="defaultPlanBoardVisible(index)" />
            <!-- 风险跟踪信息 -->
            <ComForm :form="detail" title="风险跟踪信息" :onlyRead="true" :showProjectPosition="false" :showPlanBoardVisible="true" :defaultPlanBoardVisible="defaultPlanBoardVisible(index)" />
            <!-- 风险跟踪检查信息 -->
            <ComTable :dataSource="detail.checks['gz']" v-if="detail.checks && detail.checks['gz']" :title="'风险跟踪检查信息'" :onlyRead="true" :showPlanBoardVisible="true" />
            <!-- 风险过程检查信息 -->
            <ComTable :dataSource="detail.checks['gc']" :showRiskMonitorTimeLimit="false" v-if="detail.checks && detail.checks['gc']" :title="'风险过程检查信息'" :onlyRead="true" :showPlanBoardVisible="true" />
             <!-- 验证结果 -->
             <ComResult :form="detail.result" :onlyRead="true"  v-if="detail.result" :showPlanBoardVisible="true" />
          </div>
           <!-- 验证结果 -->
           <ComResult ref="ComResultForm" :form="verifyForm" :onlyRead="false"  v-if="(editModel == '0' || editModel == '3') && form.detail && form.detail.length - 1 == index" @resultChange="resultChange" />
      </a-card>
      <a-card :bordered="false" class="base-info-style" v-if="verifyFormNext">
        <!-- 继续处理 -->
        <ComForm ref="ComFormNext" :projectId="form.projectId" :form="verifyForm" :onlyRead="false" title="继续处理" @updateForm="updateForm" />
      </a-card>
      <!-- 页脚操作栏 -->
      <Footer :editModel="editModel"  :api="api" :id="id" :templateCode="'B10003'" :needPrint="editModel == '2'" :loading="footerLoading" :onlySubmit="editModel == '0' || editModel == '3'" @submitValidate="submitValidate" />
    </a-spin>
  </base-breadcrumb>
</template>

<script>
import { riskReporting } from '@/api/quality/risk/riskReporting'
import { monitoringRecords } from '@/api/quality/risk/monitoringRecords'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BaseInfo from '@/views/quality/riskIdentification/components/BaseInfo'
import ComForm from '@/views/quality/riskIdentification/components/ComForm'
import ComResult from '@/views/quality/riskIdentification/components/ComResult'
import ComTable from '@/views/quality/riskIdentification/components/ComTable'
import Footer from '@/views/quality/riskIdentification/components/Footer'
import RiskReportingInfo from '@/views/quality/riskIdentification/components/RiskReportingInfo'
import RiskReviewInfo from '@/views/quality/riskIdentification/components/RiskReviewInfo'
import RiskTreatmentPlanInfo from '@/views/quality/riskIdentification/components/RiskTreatmentPlanInfo'
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    BaseInfo,
    ComForm,
    ComTable,
    Footer,
    RiskReportingInfo,
    RiskReviewInfo,
    RiskTreatmentPlanInfo,
    ComResult
  },
  data() {
    return {
      id: this.$route.query.id || '',
      sourceId: this.$route.query.sourceId || '',
      loading: false, // 请求加载框
      editModel: this.$route.query.editModel || '0', // 操作类型：0，1 编辑，2 查看, 3 验证
      form: {
        projectId: '',
        updateUserName: this.$userInfo().name,
        fillTime: this.$dateFormat(Date.now(), 'D'),
      },
      detailForm: {},
      verifyForm: {},
      verifyFormNext: false,
      footerLoading: { 'submitDraft': false, 'submitFormal': false, 'submitValidate': false },
      api: monitoringRecords, // 请求api
      titles: ['', '编辑', '查看', '验证'], // 根据操作类型自适应的标题
      projectId: this.$route.query.projectId || '',
      branchComName: this.$route.query.branchComName || '',
      projectName: this.$route.query.projectName || '',
    }
  },
  created() {
    this.$route.meta.title = [
      '',
      '编辑（上报风险）',
      '查看（上报风险）',
      '验证（上报风险）',
    ][this.editModel]
    // 初始化
    this.init()
  },
  computed: {
  },
  methods: {
    defaultPlanBoardVisible(index) {
      return !((this.editModel == '0' || this.editModel == '3') && this.form.detail && this.form.detail.length - 1 == index)
    },
    /**
     * @description: 初始化
     */
    init() {
      // 当操作为新增和生成整改单,则自动获取下发人和下发时间，否则请求业务详情
      if (this.id) {
        this.loading = true
        this.api
          .getDetail(this.id)
          .then((res) => {
            if (res.data) {
              // 映射表单
              this.form = res.data
            }
          })
          .finally(() => {
            this.loading = false
          })
          if (this.sourceId) {
            riskReporting
            .getDetail(this.sourceId)
            .then((res) => {
              if (res.data) {
                // 映射表单
                res.data.projectTypeId = res.data.projectTypeId ? res.data.projectTypeId.toString(): ''
                res.data.subProjectId = res.data.subProjectId ? res.data.subProjectId.toString(): ''
                res.data.viewName = res.data.branchComName + '/' + res.data.projectName
                this.detailForm = res.data
              }
            })
        }
      } else {
        this.form.fillerName = this.$userInfo()?.name
        this.form.fillerId = this.$userInfo().id
        this.form.modifiedTime = this.$dateFormat(new Date(), 'D')
        this.form.viewName = this.branchCompanyName + '/' + this.projectName
        this.form.projectId = this.projectId
      }
    },
    updateForm(e) {
      if (e) {
        this.verifyForm = Object.assign({}, this.verifyForm, e)
      }
    },
    resultChange(e) {
      if (e && e.code == '2') {
        this.verifyFormNext = true
      } else {
        this.verifyFormNext = false
      }
    },
    submitValidate() {
      const ComResultForm = this.$refs.ComResultForm
      ComResultForm?.[0].$refs?.ruleForm.validate(valid1 => {
        if (valid1) {
          if (this.verifyFormNext) {
            const ComFormNext = this.$refs.ComFormNext
            console.log(ComFormNext)
            ComFormNext.$refs?.ruleForm.validate(valid2 => {
              console.log(valid2)
              if (valid2) {
                this.submit('submitValidate')
              }
            })
          } else {
            this.submit('submitValidate')
          }
          console.log(this.verifyForm)
        }
      })
    },
    submit(status) {
      let name = 'verificate' // 根据操作切换url地址
      // 提交表单
      this.footerLoading[status] = true
      this.verifyForm.recordId = this.$route.query.id
      if (this.form.detail && this.form.detail.length) {
        this.verifyForm.recordId = this.id
        this.verifyForm.id = this.form.detail[this.form.detail.length - 1].id
      }
      return this.api[name](this.verifyForm)
        .then((res) => {
          if (res.code === 200 || res.data.code === 200) {
            this.$message.success('提交成功！')
            this.$multiTab.close()
          }
        })
        .finally(() => {
          this.footerLoading[status] = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
.title-wrapper {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  .titleName {
    margin: 0;
  }
  .anticon {
    margin-left: 5px;
    font-size: 18px;
  }
}
</style>